<?php

namespace utils;

use GuzzleHttp\Client;

class YPUpload
{
    private $operator;
    private $password;
    private $bucket;
    private $endpoint;

    public function __construct($operator, $password, $bucket, $endpoint)
    {
        $this->operator = $operator;
        $this->password = $password;
        $this->bucket = $bucket;
        $this->endpoint = $endpoint;
    }

    public function upload($file, $uri)
    {
        $client = new Client([
            'base_uri' => $this->endpoint,
        ]);

        $sign = $this->sign('PUT', '/' . $this->bucket . $uri);
        $file = str_replace("\\", "/", $file);
        return $client->put($this->bucket . $uri, [
            'headers' => [
                'Date' => gmdate('D, d M Y H:i:s \G\M\T'),
                'Authorization' => $sign,
                'Content-length' => filesize($file),
            ],
            'body' => fopen($file, 'r')
        ]);
    }

    private function sign($method, $uri, $policy = null, $md5 = null)
    {
        $date = gmdate('D, d M Y H:i:s \G\M\T');

        $elems = array();
        foreach (array($method, $uri, $date, $policy, $md5) as $v) {
            if ($v) {
                $elems[] = $v;
            }
        }
        $value = implode('&', $elems);
        $password = md5($this->password);
        $sign = base64_encode(hash_hmac('sha1', $value, $password, true));
        return 'UPYUN ' . $this->operator . ':' . $sign;
    }
}